#include "servertcp.h"
#include <QTimer>
#include <QMap>
#include <QPointer>

// 新增成员变量 m_pendingSockets 用于记录待发送的socket
QMap<QTcpSocket*, QByteArray> ServerTcp::m_pendingSockets;
QMutex ServerTcp::m_pendingMutex;

// 构造函数，启动服务器监听
ServerTcp::ServerTcp(QObject *parent)
    : QTcpServer(parent)
{
}


ServerTcp::~ServerTcp()
{
    {
        QMutexLocker lock(&m_clientsMutex);
        for (QTcpSocket* socket : m_clients) {
            socket->disconnectFromHost();
            socket->deleteLater();
        }
    }
}

bool ServerTcp::startServer(quint16 port) {
    if (!this->listen(QHostAddress::Any, port)) {
        qDebug() << "Server could not start!" << this->errorString();
        return false;
    } else {
        qDebug() << "Server started!";
        return true;
    }
}

void ServerTcp::incomingConnection(qintptr socketDescriptor)
{
    QTcpSocket *socket = new QTcpSocket(this);
    if (socket->setSocketDescriptor(socketDescriptor)) {
        qDebug() << "New client connected:" << socket->peerAddress().toString() << ":" << socket->peerPort();
        {
            QMutexLocker lock(&m_clientsMutex);
            m_clients.append(socket);
        }
        onAssignClientRequests(socket);
    } else {
        qDebug() << "Failed to set socket descriptor:" << socket->errorString();
        delete socket;
    }
}

void ServerTcp::onAssignClientRequests(QTcpSocket *m_pTcpSocket) {
    QPointer<QTcpSocket> safeSocket(m_pTcpSocket);
    connect(m_pTcpSocket, &QTcpSocket::readyRead, [=]() {
        if (!safeSocket) return;
        QMutexLocker lock(&m_bufferMutex);
        m_buffers[m_pTcpSocket] += m_pTcpSocket->readAll();
        while (m_buffers[m_pTcpSocket].contains('\n')) {
            int pos = m_buffers[m_pTcpSocket].indexOf('\n');
            QString packet = m_buffers[m_pTcpSocket].left(pos).trimmed();
            m_buffers[m_pTcpSocket] = m_buffers[m_pTcpSocket].mid(pos+1);
            QStringList parts = packet.split(',');
            if (parts.size() < 1 || parts[0] != "login") {
                qDebug() << "Invalid packet received:" << packet;
                continue;
            }
            if(parts[0] == "login") {
                QString tempUsername = parts[1];
                QString tempPassword = parts[2];
                emit onServerLogin(tempUsername, tempPassword, safeSocket);
            }
            if(parts[0] == "device") {
                emit onServerGetDevive(safeSocket);
            }
        }
    });
    connect(m_pTcpSocket, &QTcpSocket::disconnected, m_pTcpSocket, &QTcpSocket::deleteLater);
}

void ServerTcp::onRespondClientLogin(bool isActive, QTcpSocket* socket)
{
    if (!socket || socket->state() != QAbstractSocket::ConnectedState) {
            qDebug() << "Socket is not connected!";
            return;
    }
    QString response = isActive ? "login true" : "login false";
    QByteArray data = response.toUtf8() + "\n"; // 明确添加结束符
    // 记录待发送的socket
    QPointer<QTcpSocket> safeSocket(socket);
    {
        QMutexLocker lock(&m_pendingMutex);
        m_pendingSockets[safeSocket] = data;
    }
    connect(socket, &QTcpSocket::bytesWritten, [=]() {
        if (socket->bytesToWrite() == 0) {
            QTimer::singleShot(50, [=]() { // 等待缓冲区清空
                if (safeSocket) {
                    {
                        QMutexLocker lock(&m_pendingMutex);
                        m_pendingSockets.remove(safeSocket);
                    }
                        safeSocket->disconnectFromHost();
                    }
            });
        }
    });
    socket->write(data);
    connect(socket, &QTcpSocket::disconnected, [=](){
        QMutexLocker lock(&m_clientsMutex);
        m_clients.removeAll(socket);
        socket->deleteLater();
    });
}

void ServerTcp::onRespondClientDevice(QString Device, QTcpSocket *socket) {
    if (!socket || socket->state() != QAbstractSocket::ConnectedState) {
            qDebug() << "Socket is not connected!";
            return;
    }
    QByteArray data = "Device" + Device.toUtf8();
    QPointer<QTcpSocket> safeSocket(socket);
    {
        QMutexLocker lock(&m_pendingMutex);
        m_pendingSockets[safeSocket] = data;
    }
    connect(socket, &QTcpSocket::bytesWritten, [=]() {
        if (socket->bytesToWrite() == 0) {
            QTimer::singleShot(50, [=]() { // 等待缓冲区清空
                if (safeSocket) {
                    {
                        QMutexLocker lock(&m_pendingMutex);
                        m_pendingSockets.remove(safeSocket);
                    }
                        safeSocket->disconnectFromHost();
                    }
            });
        }
    });
    socket->write(data);
    connect(socket, &QTcpSocket::disconnected, [=](){
        QMutexLocker lock(&m_clientsMutex);
        m_clients.removeAll(socket);
        socket->deleteLater();
    });
}


